<?php

namespace app\controller;

use app\BaseController;
use app\model\BocSupplier;

class Supplier extends BaseController
{
    /**
     * 供应商添加.
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $post['gys_order'] = 'gys_'.date('YmdHis').rand(1001, 9999);
            $supplier_m = new BocSupplier();
            $res = $supplier_m->save($post);

            return result($res);
        }
    }

    /**
     * 供应商列表.
     */
    public function index()
    {
        $page = $this->request->get('page');
        $supplier_m = new BocSupplier();
        $res = $supplier_m->where(['is_deleted' => 1])->paginate(5, false, [], $page);
        $data = $res->toArray();

        return json(['code' => 200, 'data' => $data]);
    }

    /**
     * 查看供应商信息.
     */
    public function getone()
    {
        if ($this->request->isGet()) {
            $get = $this->request->get('id');
            $supplier_m = new BocSupplier();
            $res = $supplier_m->where('id', $get)->find();

            return result($res);
        }
    }

    public function editgetone()
    {
        if ($this->request->isGet()) {
            $get = $this->request->get('id');
            $supplier_m = new BocSupplier();
            $res = $supplier_m->where('id', $get)->find();

            return result($res);
        }
    }

    public function editres()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if ($post['id'] != '') {
                $id = $post['id'];
                unset($post['id']);
            }
            $supplier_m = new BocSupplier();
            $res = $supplier_m->where(['id' => $id])->update($post);

            return result($res);
        }
    }

    /*
     * 修改状态
     */
    public function changeState()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            try {
                $id = $post['id'];
                unset($post['id']);
                $supplier_m = new BocSupplier();
                $res = $supplier_m->where('id', $id)->save($post);
                if (!$res) {
                    throw new \Exception($res);
                }

                return result($res);
            } catch (\Exception $e) {
                return json(['code' => 400, 'msg' => $e->getMessage()]);
            }
        }
    }
}
